package pub.tbc.toolkit.collection;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import pub.tbc.toolkit.Loops;
import pub.tbc.toolkit.Objs;
import pub.tbc.toolkit.function.Consumer;

import java.util.*;

/**
 * @author tbc on 2016/8/25 10:14:14.
 */
public final class MapBuilder<K, V> {
    private class Entry {
        K k;
        V v;

        Entry(K k, V v) {
            this.k = k;
            this.v = v;
        }
    }

    private final List<Entry> tempStore = Lists.newArrayList();

    public static <K, V> MapBuilder<K, V> builder() {
        return new MapBuilder<K, V>();
    }

    public MapBuilder<K, V> put(K k, V v) {
        tempStore.add(new Entry(k, v));
        return this;
    }

    public HashMap<K, V> toHashMap() {
        if (Objs.isEmpty(tempStore)) {
            return new HashMap<K, V>();
        }
        final HashMap<K, V> hashMap = Maps.newHashMap();
        Loops.forEach(tempStore, new Consumer<Entry>() {
            @Override
            public void accept(Entry entry) {
                hashMap.put(entry.k, entry.v);
            }
        });
        return hashMap;
    }

    public LinkedHashMap<K, V> toLinkedHashMap() {
        return new LinkedHashMap<K, V>(toHashMap());
    }

    public TreeMap<K, V> toTreeMap() {
        return new TreeMap<K, V>(toHashMap());
    }

    public TreeMap<K, V> toTreeMap(Comparator<? super K> comparator) {
        TreeMap<K, V> treeMap = new TreeMap<>(comparator);
        treeMap.putAll(toHashMap());
        return treeMap;
    }

    public HashMap<K, V> build() {
        return toHashMap();
    }

    public static void main(String[] args) {
        Map<String, String> map = new MapBuilder<String, String>()
                .put("k1", "v1")
                .put("k3", "v3")
                .put("k2", "v2")
                .toTreeMap();
        String s = map.get("");
        System.out.println(map);
    }
}
